<template>
  <div class="execution">
    <basic-container>
      <div>
        <el-input size="small" v-model="key" placeholder="用户昵称/手机号/红旗会员卡号" style="width: 320px;margin-right: 20px"></el-input>
        <el-button size="small" type="primary" @click="search">搜索</el-button>
        <el-button size="small" @click="rest">重置</el-button>
      </div>
<!--      <avue-crud ref="crud"-->
<!--                 v-model="form"-->
<!--                 :page="page"-->
<!--                 :data="tableData"-->
<!--                 :table-loading="tableLoading"-->
<!--                 :option="tableOption"-->
<!--                 @current-change="currentChange"-->
<!--                 @size-change="sizeChange"-->
<!--                 @refresh-change="refreshChange"-->
<!--                 @row-update="handleUpdate"-->
<!--                 @row-save="handleSave"-->
<!--                 @row-del="rowDel">-->
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 v-model="form"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @row-del="rowDel">
        <!--<template slot="menuLeft">-->
          <!--<el-button type="primary"-->
                     <!--@click="handleAdd"-->
                     <!--size="small"-->
                     <!--v-if="permissions.usercenter_user_add">新 增</el-button>-->
          <!--<br /><br />-->
        <!--</template>-->
        <template slot="userSex"
                  slot-scope="scope">
          <el-tag v-if="scope.row.userSex==1">男</el-tag>
          <el-tag v-else-if="scope.row.userSex==2">女</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
        <template slot-scope="scope"
                  slot="menu">
          <el-button type="text"
                     icon="el-icon-check"
                     size="small"
                     plain
                     @click="handleEdit(scope.row,scope.index)">编辑</el-button>
          <el-button type="text"
                     icon="el-icon-location-outline"
                     size="small"
                     plain
                     @click="handleOpenAddressDialog(scope.row,scope.index)">地址列表</el-button>
        </template>
        <template slot="userHeadUrlForm"
                  slot-scope="scope">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :limit="1"
            :file-list="fileList"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleImageRemove">
            <!--:before-upload="uploadBefore"-->
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </avue-crud>
    </basic-container>


    <el-dialog
      title="地址列表"
      :visible.sync="dialogAddressVisible"
      width="50%"
      :before-close="handleAddressClose">
      <el-table :data="addressList" max-height="300" stripe border>
        <el-table-column label="收货人姓名" prop="userName" align="center"></el-table-column>
        <el-table-column label="收货人电话" prop="telNumber" align="center"></el-table-column>
        <el-table-column label="会员卡号" prop="member" align="center"></el-table-column>
        <el-table-column label="详细地址" prop="detailInfo" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.detailInfo}}{{scope.row.doorPlate}}</span>
          </template>
        </el-table-column>
<!--        <el-table-column align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <el-button type="text" size="small" @click="relatedCoupon(scope.row)">关联</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button size="small" @click="handleClose">取 消</el-button>-->
<!--      </span>-->
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { fetchList, getObj, addObj, putObj, delObj,searchUser } from '@/api/usercenter/user'
  import { tableOption } from '@/const/crud/usercenter/user'
  import {handleImgUrl} from '@/utils/util'
  export default {
    name: 'user',
    data() {
      return {
        tableData: [],
        headers: {
          'token': Vue.cookie.get('token')
        },
        dialogAddressVisible: false,
        addressList: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        form:{
          userHeadUrl:''
        },
        fileList:[],
        actionUrl:'',
        key:''
      }
    },
    created() {
    },
    mounted: function () {
      this.actionUrl = this.$http.adornUploadUrl()
      this.getList(this.page)
    },
    // computed: {
    //   ...mapGetters(['permissions'])
    // },
    methods: {
      getList(page) {
        this.tableLoading = true
        const data = new FormData()
        data.append('currentPage', page.currentPage)
        data.append('size',page.pageSize)
        fetchList(data).then(response => {
          console.log(response)
          this.tableData = response.data.data.list
          this.page.total = response.data.data.totalCount
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd: function() {
        this.$refs.crud.rowAdd()
      },
      handleEdit(row, index) {
        this.fileList = []
        this.form.userHeadUrl = row.userHeadUrl
        if (row.userHeadUrl) {
          if (row.userHeadUrl.startsWith('http')) {
            this.fileList = [{
              url: row.userHeadUrl
            }]
          } else {
            handleImgUrl(row.userHeadUrl).then((res) => {
              this.fileList = [{
                url: res.data
              }]
            })
          }

        }
        this.$refs.crud.rowEdit(row, index)
      },
      handleDel(row, index) {
        this.$refs.crud.rowDel(row, index)
      },
      rowDel: function(row, index) {
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=> {
            const data = new FormData()
            data.append('userId',row.id)
            delObj(data).then(res => {
              this.$message({
                showClose: true,
                message: '删除成功',
                type: 'success'
              })
              this.getList(this.page)
            })
        }).catch(function(err) { })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function(row, index, done) {
          const data = new FormData()
        data.append('userId',row.id)
        data.append('userName',row.userName)
        data.append('userSex',row.userSex)
        data.append('userHeadUrl',row.userHeadUrl)
        data.append('userCardNumber',row.userCardNumber)
        data.append('userPhone',row.userPhone)
        putObj(data).then(data => {
          this.tableData.splice(index, 1, Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          done()
          this.getList(this.page)
        })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function(row, done) {
        addObj(row).then(data => {
          this.tableData.push(Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '添加成功',
            type: 'success'
          })
          done()
          this.getList(this.page)
        })
      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.getList(this.page)
      },
      uploadBefore(file) {
        let fileName = file.name;
        if (!this.checkFileType(fileName)) {
          this.$message.error('图片类型为jpg或png格式');
          return false
        }
        const isLt1M = file.size / 1024 / 1024 < 1;

        if (!isLt1M) {
          this.$message.error('图片大小不能超过 1MB!');
          return false
        }
      },
      // 判断文件类型
      checkFileType(fileName) {
        let allowFiles = [
          '.jpg', '.jpeg', '.png'
        ]
        let index1 = fileName.lastIndexOf(".");
        let index2 = fileName.length;
        ;
        let postf = fileName.substring(index1, index2);//后缀名
        for (let i = 0; i < allowFiles.length; i++) {
          if (postf === allowFiles[i]) {
            return true
          }
        }
        return false
      },
      handleUploadSuccess(res, file) {
        this.form.userHeadUrl = res.data.bucketName + "-" + res.data.fileName;
      },
      handleImageRemove() {
        this.form.userHeadUrl = ''
      },
      search(){
          const data = new FormData()
        data.append('keyword',this.key)
        searchUser(data).then(res=>{
            if(res.data.data){
              this.tableData = res.data.data
            }else{
                this.tableData = []
            }
        })
      },
      rest(){
          this.key = ''
        this.getList(this.page)
      },
      currentChange(val) {
        this.page.currentPage = val
        this.getList(this.page)
      },
      sizeChange(val) {
        this.page.currentPage = 1
        this.page.pageSize = val
        this.getList(this.page)
      },
      handleOpenAddressDialog(row, index) {
        let data = new FormData()
        data.append('userId', row.id)
        this.$http({
          url: this.$http.adornUrl('/user/useraddress/getUserAddressList'),
          method: 'post',
          data: data
        }).then(res => {
          this.addressList = res.data.data
        })
        this.dialogAddressVisible = true
      },
      handleAddressClose() {
        this.addressList = []
        this.dialogAddressVisible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
